<template>
  <view class="container">
    <!-- 状态栏 -->
    <view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
    
    <!-- 购物车标题栏 -->
    <view class="page-header">
      <text class="page-title">购物车</text>
      <text class="header-action" @click="toggleManageMode" v-if="cartList.length > 0">{{isManageMode ? '完成' : '管理'}}</text>
    </view>
    
    <!-- 加载状态显示 -->
    <view class="loading-container" v-if="isLoading">
      <view class="loading-spinner">
        <view class="loading-bounce"></view>
      </view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 购物车内容区域 -->
    <scroll-view 
      class="cart-scroll" 
      scroll-y="true" 
      enable-back-to-top="true"
      refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      :refresher-threshold="80"
      @scrolltolower="loadMoreData"
      @refresherrefresh="onRefresh"
      :style="{ height: `calc(100% - ${statusBarHeight}px - 110rpx - 160rpx)` }"
      v-if="!isLoading"
    >
      <!-- 空白页 -->
      <view v-if="!hasLogin || empty===true" class="empty">
        <image src="/static/images/sell/emptyCart.jpg" mode="aspectFit"></image>
        <view class="empty-tips">
          <text>购物车还是空的</text>
          <navigator class="navigator" v-if="hasLogin" url="/pages/index" open-type="reLaunch">去添加商品</navigator>
          <view class="navigator" v-else @click="navToLogin">去登录</view>
        </view>
      </view>
      
      <!-- 购物车内容 -->
      <view v-else class="cart-content">
        <!-- 列表 -->
        <view class="cart-list">
          <block v-for="(item, index) in cartList" :key="item.id">
            <view
                class="cart-item"
                :class="{'b-b': index!==cartList.length-1}"
            >
              <view class="image-wrapper">
                <view v-if="item.specificationVo.deleted === 1"
                      class="status-overlay sold-out">
                  <image src="/static/images/sell/off-shelf.png" mode="aspectFit"></image>
                </view>
                <view v-else-if="Number(item.stock) === 0"
                      class="status-overlay no-stock">
                  <image src="/static/images/sell/no-stock.png" mode="aspectFit"></image>
                </view>
                <album class="product-image" width="220rpx" height="220rpx" :showExtraImages="false"
                       :images="item.images"
                       :maxCount="1" :previewEnabled="false"></album>
                <view
                    class="checkbox-wrapper"
                    @click="check('item', index)"
                >
                  <view class="checkbox-inner" :class="{checked: item.checked}"></view>
                </view>
              </view>
              <view class="item-right">
                <text class="title">{{ item.productVo.productName }}</text>
                <text class="attr">{{ item.specificationVo.specName }}</text>
                <view class="price-quantity">
                  <text class="price">¥{{ item.unitPrice }}</text>
                  <view class="quantity-control">
                    <up-number-box @change="numberChange"
                                  inputWidth="45" :min="1" :max="item.stock" v-model="item.quantity"/>
                  </view>
                </view>
              </view>
              <view class="delete-button" v-if="isManageMode" @click="deleteCartItem(index)">
                <text class="delete-icon">×</text>
              </view>
            </view>
          </block>
        </view>
        
        <!-- 底部间距 -->
        <view class="bottom-space"></view>
      </view>
    </scroll-view>
      
    <!-- 底部结算栏 - 只在购物车有商品时显示 -->
    <view class="action-section" v-if="cartList.length > 0 && !isLoading">
      <view class="select-all" @click="check('all')">
        <view class="checkbox-wrapper">
          <view class="checkbox-inner" :class="{checked: allChecked}"></view>
        </view>
        <text>全选</text>
      </view>
      <view v-if="isManageMode" class="action-btn clear-btn" @click="clearCart">
        清空购物车
      </view>
      <view v-else class="checkout-section">
        <view class="total-box">
          <text>合计:</text>
          <text class="price">¥{{ total }}</text>
        </view>
        <view class="confirm-btn" @click="createOrder">
          <view class="btn-loading" v-if="isSubmitting"></view>
          <text>{{ isSubmitting ? '处理中...' : '去结算' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 添加自定义Tabbar组件 -->
    <custom-tabbar />
  </view>
</template>

<script>
import uniNumberBox from '@/components/uni-number-box.vue'
import useUserStore from "@/store/modules/user";
import {clearCart, delCart, listCartNoPage} from "@/api/sell/cart";
import {getToken} from "@/utils/auth";
import CustomTabbar from '@/components/custom-tabbar/index.vue';

export default {
  components: {
    uniNumberBox,
    CustomTabbar
  },
  data() {
    return {
      total: 0, //总价格
      allChecked: false, //全选状态  true|false
      empty: false, //空白页现实  true|false
      cartList: [],
      isManageMode: false, // 管理模式，显示删除按钮
      statusBarHeight: 0, // 状态栏高度
      isRefreshing: false, // 下拉刷新状态
      isLoading: true, // 页面加载状态
      isSubmitting: false, // 提交订单状态
    };
  },
  // 页面加载时获取状态栏高度
  onLoad() {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight || 0;
  },
  async onShow() {
    // 每次都重置删除模式
    this.isManageMode = false;
    
    // 直接加载数据，不做时间判断
    console.log('页面显示，加载数据');
    this.isLoading = true;
    
    // 添加延迟以展示加载效果
    setTimeout(() => {
      this.loadData()
        .then(() => {
          console.log('数据加载完成');
        })
        .catch(error => {
          console.error('数据加载失败', error);
        })
        .finally(() => {
          this.isLoading = false;
        });
    }, 600);
  },
  onHide() {
    console.log('页面隐藏');
  },
  watch: {
    //显示空白页
    cartList(e) {
      let empty = e.length === 0 ? true : false;
      if (this.empty !== empty) {
        this.empty = empty;
      }
    }
  },
  computed: {
    hasLogin: () => !!getToken()
  },
  methods: {
    //请求数据
    async loadData() {
      if (!this.hasLogin) {
        return Promise.resolve();
      }
      
      return new Promise((resolve, reject) => {
        listCartNoPage()
          .then(({data: list}) => {
            let cartList = list.map(item => {
              item.checked = true;
              return item;
            });
            this.cartList = cartList;
            this.calcTotal();  //计算总价
            resolve();
          })
          .catch(error => {
            console.error('加载购物车数据失败:', error);
            uni.showToast({
              title: '加载失败，请重试',
              icon: 'none'
            });
            reject(error);
          });
      });
    },
    //监听image加载完成
    onImageLoad(key, index) {
      this.$set(this[key][index], 'loaded', 'loaded');
    },
    //监听image加载失败
    onImageError(key, index) {
      this[key][index].image = '/static/errorImage.jpg';
    },
    navToLogin() {
      uni.navigateTo({
        url: '/pages/login'
      })
    },
    //选中状态处理
    check(type, index) {
      if (type === 'item') {
        this.cartList[index].checked = !this.cartList[index].checked;
      } else {
        const checked = !this.allChecked
        const list = this.cartList;
        list.forEach(item => {
          item.checked = checked;
        })
        this.allChecked = checked;
      }
      this.calcTotal(type);
    },
    //数量
    numberChange() {
      this.$nextTick(() => {
        this.calcTotal();
      })
    },
    //删除
    deleteCartItem(index) {
      let list = this.cartList;
      let row = list[index];
      uni.showLoading({
        title: '删除中...'
      })
      delCart(row.id).then(() => {
        this.cartList.splice(index, 1);
        this.calcTotal();
        uni.hideLoading();
        
        // 添加删除成功的动画反馈
        uni.showToast({
          title: '删除成功',
          icon: 'none'
        });
      }).catch(error => {
        uni.hideLoading();
        uni.showToast({
          title: '删除失败，请重试',
          icon: 'none'
        });
      })
    },
    //清空
    clearCart() {
      this.$confirmDialog.confirm('确定要清空购物车吗？').then(() => {
        uni.showLoading({
          title: '清空中...'
        })
        clearCart().then(res => {
          this.cartList = [];
          this.isManageMode = false;
          uni.hideLoading();
          
          // 添加清空成功的动画反馈
          uni.showToast({
            title: '购物车已清空',
            icon: 'none'
          });
        }).catch(error => {
          uni.hideLoading();
          uni.showToast({
            title: '操作失败，请重试',
            icon: 'none'
          });
        })
      })
    },
    //计算总价
    calcTotal() {
      let list = this.cartList;
      if (list.length === 0) {
        this.empty = true;
        return;
      }
      let total = 0;
      let checked = true;
      list.forEach(item => {
        if (item.checked === true) {
          total += (Number(item.unitPrice) * Math.min(Number(item.quantity), Number(item.stock)));
        } else if (checked === true) {
          checked = false;
        }
      })
      this.allChecked = checked;
      this.total = Number(total.toFixed(2));
    },
    //创建订单
    createOrder() {
      let list = this.cartList;
      let goodsList = [];
      
      // 避免重复提交
      if (this.isSubmitting) {
        return;
      }
      
      this.isSubmitting = true;
      
      for (let item of list) {
        if (item.checked) {
          if (item.specificationVo.deleted === 1) {
            this.$modal.msgError("存在已下架商品");
            this.isSubmitting = false;
            return;
          }
          if (Number(item.stock) === 0) {
            this.$modal.msgError("存在无库存商品");
            this.isSubmitting = false;
            return;
          }
          if (Number(item.quantity) > Number(item.stock)) {
            this.$modal.msgError("存在超库存商品");
            this.isSubmitting = false;
            return;
          }
          goodsList.push({
            cartId: item.id,
            id: item.specificationVo.id,
            productId: item.productVo.id,
            name: item.specificationVo.specName,
            itemName: item.productVo.productName,
            images: item.specificationVo.specImage,
            buyQuantity: item.quantity,
            sellingPrice: item.unitPrice
          })
        }
      }
      if (goodsList.length === 0) {
        this.$modal.msgError("请选择商品");
        this.isSubmitting = false;
        return;
      }
      
      // 添加延迟以显示加载效果
      setTimeout(() => {
        this.globalData.goodsList = goodsList;
        uni.navigateTo({
          url: `/pages/sellment/order/createOrder`
        });
        this.isSubmitting = false;
      }, 600);
    },
    //下拉刷新
    async onRefresh() {
      if (this.isRefreshing) return;
      
      this.isRefreshing = true;
      
      try {
        await this.loadData();
        uni.showToast({
          title: '刷新成功',
          icon: 'none'
        });
      } catch (error) {
        console.error('刷新失败:', error);
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      } finally {
        this.isRefreshing = false;
      }
    },
    loadMoreData() {
        // 此处暂不实现分页逻辑，因为当前API不支持分页
        console.log('滚动到底部');
    },
    toggleManageMode() {
      this.isManageMode = !this.isManageMode;
    }
  }
}
</script>

<style lang='scss'>
page {
  height: 100%;
}

/* 关键帧动画定义 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    opacity: 0;
    transform: translateY(20rpx);
  }
  to { 
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-15rpx); }
}

@keyframes shine {
  0% { left: -100%; opacity: 0.6; }
  100% { left: 100%; opacity: 0; }
}

.container {
  display: flex;
  flex-direction: column;
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

/* 状态栏样式 */
.status-bar {
  width: 100%;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(15rpx);
  position: relative;
  z-index: 10;
  animation: fadeIn 0.5s ease-out;
}

/* 页面标题栏 */
.page-header {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 40rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(15rpx);
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.02);
  z-index: 10;
  height: 110rpx;
  box-sizing: border-box;
  animation: fadeIn 0.5s ease-out;
  
  .page-title {
    font-size: 38rpx;
    font-weight: 600;
    color: #333;
    letter-spacing: 1rpx;
  }
  
  .header-action {
    font-size: 26rpx;
    padding: 10rpx 24rpx;
    background: rgba(255, 107, 0, 0.08);
    border: 1rpx solid rgba(255, 107, 0, 0.2);
    color: #FF6B00;
    border-radius: 30rpx;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.96);
      background: rgba(255, 107, 0, 0.12);
    }
  }
}

/* 加载动画样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 240rpx);
  animation: fadeIn 0.5s ease-out;
  
  .loading-spinner {
    width: 80rpx;
    height: 80rpx;
    position: relative;
    margin-bottom: 20rpx;
    
    .loading-bounce {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: rgba(255, 107, 0, 0.6);
      opacity: 0.6;
      position: absolute;
      top: 0;
      left: 0;
      animation: bounce 2s infinite ease-in-out;
      
      &:before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: rgba(255, 107, 0, 0.6);
        opacity: 0.6;
        animation: bounce 2s infinite ease-in-out;
        animation-delay: -1.0s;
      }
    }
  }
  
  .loading-text {
    color: #999;
    font-size: 28rpx;
  }
}

@keyframes bounce {
  0%, 100% { 
    transform: scale(0);
  }
  50% { 
    transform: scale(1.0);
  }
}

/* 滚动区域 */
.cart-scroll {
  flex: 1;
  box-sizing: border-box;
}

/* 空白页 */
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 15vh;
  position: relative;
  z-index: 2;
  min-height: 80vh;
  animation: fadeIn 0.5s ease-out;

  image {
    width: 320rpx;
    height: 240rpx;
    margin-bottom: 40rpx;
    opacity: 0.85;
    animation: float 4s ease-in-out infinite;
  }

  .empty-tips {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    text {
      font-size: 30rpx;
      color: #999;
      margin-bottom: 30rpx;
      letter-spacing: 2rpx;
    }

    .navigator {
      position: relative;
      color: #FF6B00;
      background: linear-gradient(to right, rgba(255, 123, 0, 0.08), rgba(255, 107, 0, 0.06));
      padding: 22rpx 60rpx;
      border-radius: 50rpx;
      font-size: 28rpx;
      letter-spacing: 1rpx;
      box-shadow: 0 6rpx 20rpx rgba(255, 107, 0, 0.1);
      overflow: hidden;
      transition: all 0.3s;
      
      /* 动态光效 */
      &::after {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: linear-gradient(
          to right, 
          rgba(255, 255, 255, 0) 0%, 
          rgba(255, 255, 255, 0.3) 50%, 
          rgba(255, 255, 255, 0) 100%
        );
        transform: rotate(30deg);
        animation: shine 3s infinite linear;
      }
      
      &:active {
        transform: translateY(2rpx);
        box-shadow: 0 2rpx 10rpx rgba(255, 107, 0, 0.1);
      }
    }
  }
}

/* 购物车内容 */
.cart-content {
  padding-bottom: 100rpx;
  animation: fadeIn 0.5s ease-out;
}

/* 购物车列表 */
.cart-list {
  padding: 20rpx 40rpx;
  position: relative;
  z-index: 2;
}

/* 购物车列表项添加进场动画 */
.cart-item {
  display: flex;
  position: relative;
  padding: 30rpx;
  margin: 0 6rpx 24rpx 6rpx;
  background-color: white;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.03);
  overflow: hidden;
  animation: slideUp 0.5s ease-out;
  opacity: 0;
  animation-fill-mode: forwards;
  
  @for $i from 1 through 10 {
    &:nth-child(#{$i}) {
      animation-delay: #{$i * 0.05}s;
    }
  }
  
  /* 装饰色块 */
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 6rpx;
    height: 100%;
    background: linear-gradient(to bottom, #FF7B00, #FF6B00);
    opacity: 0.8;
  }

  .image-wrapper {
    width: 220rpx;
    height: 220rpx;
    flex-shrink: 0;
    position: relative;
    margin-right: 25rpx;
    
    .product-image {
      width: 100%;
      height: 100%;
      border-radius: 16rpx;
      overflow: hidden;
      box-shadow: 0 6rpx 15rpx rgba(0, 0, 0, 0.05);
    }
    
    .status-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(255, 255, 255, 0.85);
      border-radius: 16rpx;
      z-index: 5;
      backdrop-filter: blur(2rpx);
      
      image {
        width: 110rpx;
        height: 110rpx;
        opacity: 0.8;
      }
    }
  }

  .checkbox-wrapper {
    position: absolute;
    left: -8rpx;
    top: -8rpx;
    width: 48rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    border-radius: 50%;
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.06);
    z-index: 6;
    
    .checkbox-inner {
      width: 26rpx;
      height: 26rpx;
      border-radius: 50%;
      border: 2rpx solid #ddd;
      transition: all 0.15s;
      
      &.checked {
        border-color: #FF6B00;
        background-color: #FF6B00;
        box-shadow: inset 0 0 0 3rpx #fff;
      }
    }
  }

  .item-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding-right: 10rpx;

    .title {
      font-size: 30rpx;
      color: #333;
      font-weight: 500;
      line-height: 1.5;
      margin-bottom: 12rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      word-break: break-all;
      text-overflow: ellipsis;
    }

    .attr {
      display: inline-block;
      font-size: 24rpx;
      color: #888;
      padding: 6rpx 16rpx;
      background: rgba(0, 0, 0, 0.035);
      border-radius: 20rpx;
      margin-bottom: 20rpx;
      max-width: 100%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .price-quantity {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: auto;
      
      .price {
        font-size: 34rpx;
        color: #FF6B00;
        font-weight: 600;
        font-family: 'DIN Condensed', Arial, sans-serif;
      }
      
      .quantity-control {
        margin-right: -10rpx;
      }
    }
  }
  
  .delete-button {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    width: 46rpx;
    height: 46rpx;
    background: rgba(0, 0, 0, 0.6);
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 6;
    
    .delete-icon {
      font-size: 32rpx;
      font-weight: bold;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
}

/* 底部结算栏 */
.action-section {
  position: fixed;
  left: 40rpx;
  right: 40rpx;
  bottom: 130rpx;
  z-index: 95;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  border-radius: 50rpx;
  box-shadow: 
    0 8rpx 20rpx rgba(0, 0, 0, 0.1),
    0 12rpx 25rpx rgba(0, 0, 0, 0.08),
    0 4rpx 15rpx rgba(255, 107, 0, 0.08);
  animation: slideUp 0.5s ease-out;
  animation-delay: 0.2s;
  opacity: 0;
  animation-fill-mode: forwards;
  
  .select-all {
    display: flex;
    align-items: center;
    
    .checkbox-wrapper {
      width: 44rpx;
      height: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16rpx;
      
      .checkbox-inner {
        width: 26rpx;
        height: 26rpx;
        border-radius: 50%;
        border: 2rpx solid #ddd;
        transition: all 0.15s;
        
        &.checked {
          border-color: #FF6B00;
          background-color: #FF6B00;
          box-shadow: inset 0 0 0 3rpx #fff;
        }
      }
    }
    
    text {
      font-size: 28rpx;
      color: #444;
      font-weight: 500;
    }
  }
  
  .checkout-section {
    display: flex;
    align-items: center;
    
    .total-box {
      margin-right: 25rpx;
      text-align: right;
      
      text {
        font-size: 28rpx;
        color: #444;
      }
      
      .price {
        font-weight: 600;
        font-size: 36rpx;
        color: #FF6B00;
        margin-left: 8rpx;
        font-family: 'DIN Condensed', Arial, sans-serif;
      }
    }
  }
  
  .confirm-btn {
    padding: 0 40rpx;
    height: 70rpx;
    line-height: 70rpx;
    text-align: center;
    background: linear-gradient(135deg, #FF7B00, #FF6B00);
    color: #fff;
    font-size: 28rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    border-radius: 35rpx;
    box-shadow: 
      0 6rpx 15rpx rgba(255, 107, 0, 0.25),
      0 8rpx 20rpx rgba(255, 107, 0, 0.15);
    position: relative;
    overflow: hidden;
    transition: all 0.2s;
    
    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 3rpx 8rpx rgba(255, 107, 0, 0.2);
    }
  }
  
  .action-btn {
    padding: 0 40rpx;
    height: 70rpx;
    line-height: 70rpx;
    text-align: center;
    background: linear-gradient(135deg, #FF7B00, #FF6B00);
    color: #fff;
    font-size: 28rpx;
    letter-spacing: 2rpx;
    border-radius: 35rpx;
    box-shadow: 
      0 6rpx 15rpx rgba(255, 107, 0, 0.25),
      0 8rpx 20rpx rgba(255, 107, 0, 0.15);
    transition: all 0.2s;
    
    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 3rpx 8rpx rgba(255, 107, 0, 0.2);
    }
  }
  
  .clear-btn {
    margin-left: auto;
  }
}

/* 底部空白区域 */
.bottom-space {
  height: 120rpx;
}
</style>
